﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Telerik.Web.Mvc;

namespace Presentation.Web.Admin.Controllers
{
    [HandleError]
    public class AdvertiseController : Infrastructure.Crosscutting.NetFramework.Controllers.BaseController
    {
        Application.Admin.Advertise.IAdvertisePicService adPicService;

        Application.Admin.Advertise.IAdvertiseService adService;

        Application.Admin.Pic.IPicInfoService picService;

        public AdvertiseController(Infrastructure.Crosscutting.NetFramework.IWorkContext work,
            Application.Admin.Advertise.IAdvertisePicService adPic,
            Application.Admin.Advertise.IAdvertiseService ad,
            Application.Admin.Pic.IPicInfoService pic)
            : base(work)
        {
            if (adPic == null)
            {
                throw new ArgumentNullException("adPicService is null");
            }
            if (ad == null)
            {
                throw new ArgumentNullException("adService is null");
            }
            if (pic == null)
            {
                throw new ArgumentNullException("picService is null");
            }
            adPicService = adPic;
            adService = ad;
            picService = pic;
        }

        #region ad

        public ActionResult Index()
        {
            var data = this.GetAdvertiseTrueState();
            return View(data.ToDto());
        }

        [GridAction]
        public JsonResult AjaxIndex(string searchKey)
        {
            var data = this.GetAdvertiseTrueState();
            if (!string.IsNullOrEmpty(searchKey))
            {
                data = data.Where(e => e.Name.Contains(searchKey));
            }
            var dto = data.ToDto();
            var model = new GridModel<Domain.Dto.AdvertiseDto>
            {
                Data = dto,
                Total = dto.Count()
            };
            return new JsonResult { Data = model, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
        }

        [HttpPost]
        public JsonResult Add(Domain.Dto.AdvertiseDto dto)
        {
            var res = false;
            var message = "";
            if (!string.IsNullOrEmpty(dto.Name) && dto != null)
            {
                var entity = dto.ToEntity();
                entity.AddTime = System.DateTime.Now;
                entity.IpAddress = Infrastructure.Crosscutting.Comm.Service.StringService.GetRealIP();
                entity.Name = dto.Name.Trim();
                entity.Remark = string.IsNullOrEmpty(dto.Remark) ? "" : dto.Remark.Trim();
                entity.SortNum = 0;
                entity.State = true;
                entity.Url = string.IsNullOrEmpty(dto.Url) ? "" : dto.Url.Trim();
                adService.Add(entity, this.WorkContext.CurrentUser);
                if (entity.Id > 0)
                {
                    res = true;
                }
                else
                {
                    message = "添加失败T_T";
                }
            }
            else
            {
                message = "广告名不能为空";
            }
            return Json(new { success = res, message = message }, JsonRequestBehavior.AllowGet);
        }

        [GridAction]
        [HttpPost]
        public JsonResult Delete(int id)
        {
            var delete = adService.Get(id);
            if (delete != null)
            {
                adService.DeleteTrue(delete, this.WorkContext.CurrentUser);
            }
            var data = this.GetAdvertiseTrueState().ToDto();
            return Json(data, JsonRequestBehavior.AllowGet);
        }

        [HttpPost]
        public JsonResult MulDelete(FormCollection del)
        {
            var res = false;
            var message = "";
            var selectedList = del.GetValues("selectRow");
            if (selectedList != null && selectedList.Count() > 0)
            {
                res = adService.DeleteTrue(selectedList.ToIntList(), this.WorkContext.CurrentUser);
                message = res == true ? "" : "删除失败了，T_T";
            }
            //返回空，是为了不再请求数据，因为他自己会重新binding的
            return Json(new { success = res, message = message }, JsonRequestBehavior.AllowGet);
        }

        [GridAction]
        [HttpPost]
        public JsonResult Edit(Domain.Dto.AdvertiseDto dto)
        {
            if (dto.Id > 0 && !string.IsNullOrEmpty(dto.Name))
            {
                var entity = adService.Get(dto.Id);
                if (entity != null && entity.Id > 0)
                {
                    entity.Name = dto.Name.Trim();
                    entity.Remark = string.IsNullOrEmpty(dto.Remark) ? "" : dto.Remark.Trim();
                    entity.Url = string.IsNullOrEmpty(dto.Url) ? "" : dto.Url.Trim();
                    entity.ExpiredDateTime = dto.ExpiredDateTime;
                    adService.Modify(entity, this.WorkContext.CurrentUser);
                }
            }
            var data = this.GetAdvertiseTrueState();
            var model = new GridModel<Domain.Dto.AdvertiseDto>
            {
                Data = data.ToDto(),
                Total = data.Count()
            };
            return new JsonResult { Data = model, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
        }

        [HttpGet]
        public JsonResult Search(string term)
        {
            if (!string.IsNullOrEmpty(term))
            {
                var data = this.GetAdvertiseTrueState().Where(e => e.Name.Contains(term.Trim()))
                            .OrderBy(e => e.Id).Take(10)
                            .Select(e => e.Name).Distinct();
                return Json(data.ToList(), JsonRequestBehavior.AllowGet);
            }
            else
            {
                var data = this.GetAdvertiseTrueState().OrderBy(e => e.Id).Take(10)
                            .Select(e => e.Name).Distinct();
                return Json(data.ToList(), JsonRequestBehavior.AllowGet);
            }
        }

        #endregion

        #region advertise pic pre view

        public JsonResult AdvertisePicView(int id)
        {
            var res = false;
            var path = "";
            var message = "";
            var width = 0;
            var height = 0;
            var picId = adPicService.GetList().Where(e => e.AdverseId == id)
                .OrderByDescending(e => e.Id)
                .ThenByDescending(e => e.AddTime)
                .Select(e => e.PicInfoId)
                .FirstOrDefault();
            var pic = picService.Get(picId);
            if (pic != null)
            {
                path = pic.WebFullPath;
                var phyPath = Server.MapPath("~" + path);
                var exist = System.IO.File.Exists(phyPath);
                if (exist)
                {
                    System.Drawing.Image image = System.Drawing.Image.FromFile(phyPath);
                    if (image != null)
                    {
                        width = image.Width;
                        height = image.Height;
                        image.Dispose();
                    }
                    res = true;
                }
                else
                {
                    message = "物理文件已经被删除了";
                }
            }
            else
            {
                message = "没有找到，你要浏览的图片地址T_T！，快去添加一张吧！";
            }
            return Json(new { success = res, width = width, height = height, path = path, message = message }, JsonRequestBehavior.AllowGet);
        }

        #endregion


        #region util

        private IQueryable<Domain.Entity.Advertise> GetAdvertiseTrueState()
        {
            var data = adService.GetList().Where(e => e.State == true).OrderByDescending(e => e.Id);
            return data;
        }

        #endregion
    }
}
